<template>
  <div class="wrapper">
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="onTabChange">
      <el-tab-pane v-for="item in tabsList" :key="item.value" :label="item.label" :name="item.value" />
    </el-tabs>
    <div class="header" v-if="activeName === 'current'">
      <div>
        <span class="header-title" v-show="!isAll">
          应提交：
          <span>{{ countInfo.countAll }}</span>
        </span>
        <span class="header-title" v-show="!isAll">
          已提交：
          <span>{{ countInfo.submitCount }}</span>
        </span>
        <span class="header-title" v-show="!isAll">
          未提交：
          <span>{{ countInfo.noSubmitCount }}</span>
        </span>
        <span class="text-blue">{{ countInfo.selectDay }}</span>
      </div>
      <el-divider />
    </div>
    <div class="search-box" v-else-if="activeName === 'history'">
      <el-select
        clearable
        v-model="selectUserLabel"
        @change="userChange"
        filterable
        style="width: 240px; margin-right: 12px">
        <template #prefix>
          <SvgIcon name="user"></SvgIcon>
        </template>
        <el-option
          v-for="item in projectMemberList"
          :key="item.userId"
          :label="item.userName"
          :value="item.userId"></el-option>
      </el-select>

      <el-date-picker
        v-model="selectDate"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
        placeholder="请选择日期"
        @change="dateChange"></el-date-picker>
      <el-divider />
    </div>
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%" border :cell-style="wrStatusCellStyle" v-loading="isLoading">
        <template v-for="(item, index) in column" :key="index">
          <el-table-column :prop="item.prop" :label="item.label" align="center" :width="item.width">
            <template v-if="item.prop === 'wrStatus'" #default="scope">
              <span class="title-weight">{{ formatReportStatus(scope.row.wrStatus)['label'] }}</span>
            </template>
            <template v-else-if="item.prop === 'wrHours'" #default="scope">
              <span class="title-weight" :style="{ color: formatReportStatus(scope.row.wrStatus)['color'] }">
                {{ scope.row.wrHours }}
              </span>
            </template>
            <template v-else-if="item.prop === 'noSubmitCount'" #default="scope">
              <span class="title-weight noSubmitCount" @click="lostUserClick(scope.row)">
                {{ scope.row.noSubmitCount }}
              </span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" align="center" v-if="activeName !== 'lost'">
          <template #default="{ row }">
            <el-button
              v-if="row.replyFlag === '未读' && row.wrStatus"
              link
              type="primary"
              @click="reviewClick(row, 'review')">
              查阅
            </el-button>
            <el-button v-else link type="primary" @click="reviewClick(row, 'view')">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" v-if="activeName !== 'lost'">
        <el-pagination
          v-model:current-page="queryInfo.params.pageNum"
          v-model:page-size="queryInfo.params.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="dataTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <TaskChatDialog :model-value="userVisible" title="未提交" width="40%" @close="userVisible = false" append-to-body>
      <div class="user-content">
        <el-tag class="user-content-tag" v-for="(item, index) in lostList" :key="index" size="large">
          {{ item.nickName }}
        </el-tag>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userVisible = false">取消</el-button>
          <el-button type="primary" @click="remind">一键提醒</el-button>
        </span>
      </template>
    </TaskChatDialog>

    <ReportReview ref="reviewRef" v-model="reviewVisivle" @refresh="refresh"></ReportReview>
  </div>
</template>

<script setup>
import { formatReportStatus } from '@/utils/task-utils'
import ReportReview from '@/views/project/components/project-setting/ReportReview'
import { getTcDailyReportList, getTcDailyReportCount, getTcDailyReportNoSubmit } from '@/assets/api/report'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getProjectMember } from '@/assets/api/project'

const props = defineProps({
  projectId: String,
  isAll: {
    type: Boolean,
    default: false,
  },
})

const currentPrjectId = ref('')

watch(
  () => props.projectId,
  (n, o) => {
    currentPrjectId.value = n + ''
    getTableData()
    getReportCount(1)
  },
  { deep: true }
)

const currentDay = ref(dayjs().format('YYYY-MM-DD'))

const activeName = ref('current')
const tabsList = ref([
  { label: '当前日报', value: 'current' },
  { label: '本周缺失', value: 'lost' },
  { label: '历史记录', value: 'history' },
])

const isLoading = ref(false)
const tableData = ref([])
const column = ref([])
const reportColumn = [
  { prop: 'userName', label: '姓名' },
  { prop: 'selectDay', label: '日报日期' },
  { prop: 'wrStatus', label: '类型' },
  { prop: 'wrHours', label: '登记工时' },
  { prop: 'createdTime', label: '提交时间', width: 200 },
  { prop: 'replyFlag', label: '状态' },
]
const weekLostColumn = [
  { prop: 'selectDay', label: '日期' },
  { prop: 'countAll', label: '应提交' },
  { prop: 'submitCount', label: '已提交' },
  { prop: 'noSubmitCount', label: '未提交' },
]

const queryInfo = reactive({
  data: {
    // userId: 1,
    projectId: props.projectId,
    selectDay: currentDay.value,
  },
  params: {
    pageSize: 10,
    pageNum: 1,
  },
})
const dataTotal = ref(0)
async function getTableData() {
  isLoading.value = true
  const res = await getTcDailyReportList(queryInfo)
  if (res.code === 200) {
    tableData.value = res.rows || []
    dataTotal.value = res.total || 0
    isLoading.value = false
  }
}

function handleSizeChange(val) {
  queryInfo.params.pageSize = val
  getTableData()
}
function handleCurrentChange(val) {
  queryInfo.params.pageNum = val
  getTableData()
}

const countInfo = reactive({
  countAll: 0,
  submitCount: 0,
  noSubmitCount: 0,
  selectDay: '',
})
async function getReportCount(type) {
  let form = {
    projectId: currentPrjectId.value || props.projectId,
    countFlag: type,
  }
  const { rows } = await getTcDailyReportCount(form)
  if (type === 1 && Array.isArray(rows) && rows.length > 0) {
    countInfo.countAll = rows[0]['countAll']
    countInfo.submitCount = rows[0]['submitCount']
    countInfo.noSubmitCount = rows[0]['noSubmitCount']
    countInfo.selectDay = rows[0]['selectDay']
  } else if (type === 2 && Array.isArray(rows) && rows.length > 0) {
    tableData.value = rows || []
  }
}

function refresh() {
  getReportCount(1)
  getTableData()
}

function onTabChange(val) {
  tableData.value = []
  activeName.value = val
  queryInfo.params = {
    pageSize: 10,
    pageNum: 1,
  }
  delete queryInfo.data.userId
  if (val === 'current') {
    column.value = reportColumn
    queryInfo.data.selectDay = currentDay.value
    getReportCount(1)
    getTableData()
  } else if (val === 'history') {
    column.value = reportColumn
    queryInfo.data.selectDay = ''
    getTableData()
  } else if (val === 'lost') {
    column.value = weekLostColumn
    getReportCount(2)
  }
}

const reviewVisivle = ref(false)
const reviewRef = ref()
async function reviewClick(row, type) {
  reviewVisivle.value = true
  reviewRef.value.open(row, type)
}

function wrStatusCellStyle({ row, column, rowIndex, columnIndex }) {
  if (activeName.value !== 'lost') {
    let style = {
      backgroundColor: formatReportStatus(row.wrStatus)['color'],
      color: '#fff',
    }
    if (columnIndex === 2) return style
  }
}

async function getNoSubmitUser(projectId, selectDay) {
  const { rows } = await getTcDailyReportNoSubmit({
    selectDay: selectDay,
    projectId,
  })
  lostList.value = rows || []
}

const userVisible = ref(false)
const lostList = ref([])
function lostUserClick(row) {
  if (row.noSubmitCount) {
    getNoSubmitUser(currentPrjectId.value || props.projectId, row.selectDay)
    userVisible.value = true
  }
}

function remind() {
  ElMessage.success('提醒成功')
  userVisible.value = false
}

const selectUserLabel = ref('')
const selectDate = ref('')
const projectMemberList = ref([])
function getProjectMemberData() {
  //查询项目成员
  getProjectMember({ projectId: props.projectId }).then((res) => {
    if (res.code === 200) {
      projectMemberList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function userChange(val) {
  if (val) {
    queryInfo.data.userId = val
  } else {
    delete queryInfo.data.userId
  }
  getTableData()
}

function dateChange(val) {
  queryInfo.data.selectDay = selectDate.value
  getTableData()
}

// const debounce = (fn, delay) => {
//   let timer = null
//   return function () {
//     let context = this
//     let args = arguments
//     clearTimeout(timer)
//     timer = setTimeout(function () {
//       fn.apply(context, args)
//     }, delay)
//   }
// }
// const _ResizeObserver = window.ResizeObserver
// window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
//   constructor(callback) {
//     callback = debounce(callback, 16)
//     super(callback)
//   }
// }

function getModuleConfig() {
  if (props.isAll) {
    tabsList.value = [
      { label: '当前日报', value: 'current' },
      { label: '历史记录', value: 'history' },
    ]
  }
}

onMounted(() => {
  column.value = reportColumn
  getModuleConfig()
  getTableData()
  getReportCount(1)
  getProjectMemberData()
})
</script>

<style lang="scss" scoped>
.wrapper {
  height: 100%;
  overflow: auto;
}
.header {
  &-title {
    display: inline-block;
    margin-right: 20px;
  }
}

.title-weight {
  font-weight: 700;
}

.pagination {
  margin-top: 40px;
}

.noSubmitCount {
  color: red;
  cursor: pointer;
}

.user-content {
  &-tag {
    margin: 10px;
  }
}

:deep(.elp-divider) {
  margin: 15px 0 !important;
}

.elp-pagination {
  justify-content: center;
}
</style>
